﻿using System;
using System.Diagnostics.Contracts;
using System.Text;

namespace CDC.SampleShell
{
    public static class Common
    {
        private static string _cachedMacAddress = String.Empty;

        public static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            Contract.Requires(source != null);

            return source.IndexOf(toCheck, comp) >= 0;
        }

        /// <summary>
        /// Finds the MAC address of the NIC with maximum speed.
        /// </summary>
        /// <returns>The MAC address</returns>
        public static string GetMacAddress()
        {
            if (!String.IsNullOrEmpty(_cachedMacAddress)) return _cachedMacAddress; // use cached MAC address to improve performance

            const int MIN_MAC_ADDR_LENGTH = 12;
            string macAddress = string.Empty;
            long maxSpeed = -1;

            foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                string tempMac = nic.GetPhysicalAddress().ToString();
                if (nic.Speed > maxSpeed &&
                    !string.IsNullOrEmpty(tempMac) &&
                    tempMac.Length >= MIN_MAC_ADDR_LENGTH)
                {
                    maxSpeed = nic.Speed;
                    macAddress = tempMac;
                }
            }

            _cachedMacAddress = macAddress;

            return macAddress;
        }
    }
}
